package o2o.task.order;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ValidateUtil;
import com.jinyouapp.client.tel.TelCallClient;
import com.jinyouapp.client.tel.exception.TelCallException;
import com.jinyouapp.client.tel.model.TtsCallResponseInfo;
import map.HttpRequest;
import o2o.business.dispatch.DispatchPostmanBusinessV2;
import o2o.cache.agent.AgentOrderOverTimeMemory;
import o2o.cache.order.OrderInfoExtraMemory;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.order.OrderPolicyRecordMemory;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.sys.SysCustomerCache;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.OrderOverTimeInfo;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.order.*;
import o2o.dao.PO.policy.INSURANCE_STATUS;
import o2o.dao.PO.policy.PolicyInfo;
import o2o.postman.model.CityPostman;
import o2o.company.model.ShopInfo;
import o2o.dao.TO.policy.PolicyResultDto;
import o2o.dao.VO.order.OrderGoodsVO;
import o2o.dao.VO.order.REFUND_APPLY_STATUS;
import o2o.dao.VO.policy.PolicyInfoVO;
import o2o.service.delivery.to.DeliveryOrderStateTO;
import o2o.service.order.shop.ShopOrderService;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.web.actions.notice.PONE_NOTICE_TYPE;
import o2o.web.actions.notice.PhoneNotice;
import o2o.web.actions.order.OrderMan;
import org.apache.commons.lang.StringUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class OrderTaskUtil {

    // 骑手优先抢单问题
    public static List<OrderInfo> checkPostManLikeList = new ArrayList<>();

    // 平台中进行中的订单
    public static List<OrderInfo> platformIngOrderList = new ArrayList<>();

    // 需要派单的订单
    private static HashSet<String> needDispatchOrderSet = new HashSet<>();

    // 检测订单时间是不是大于设定时间
    // 几分钟后，收藏者不接单，再让平台其他骑手一起参与
    public static void checkOrder() {
        List<OrderInfo> orderInfoList = new ArrayList<>();
        synchronized (checkPostManLikeList) {  //获得list锁对象，其他线程将不能获得list锁来来改变list对象。
            if (ValidateUtil.isAbsList(checkPostManLikeList)) {
                orderInfoList.addAll(checkPostManLikeList);
            }
            checkPostManLikeList = new ArrayList<>();
        }
        if (ValidateUtil.isAbsList(orderInfoList)) {
            for (OrderInfo orderInfo : orderInfoList) {
                if (orderInfo == null) {
                    continue;
                }
                if (SYS_SETTINGS.LIKE_POSTMAN_UNROB_TIME == null
                        || SYS_SETTINGS.LIKE_POSTMAN_UNROB_TIME <= 0) {
                    System.out.print("收藏骑手未接单后：未设置时间");
                    return;
                }
                long time = orderInfo.getShopSureTime();
                if (!ValidateUtil.isAbsLong(time)) {
                    time = orderInfo.getPayTime();
                }
                if (!ValidateUtil.isAbsLong(time)) {
                    time = orderInfo.getCreateTime();
                }
                if (DateUtils.getCurrTime() - time >= SYS_SETTINGS.LIKE_POSTMAN_UNROB_TIME * 60 * 1000) {
                    // 修改
                    updateIsSpecifiedPostmen(orderInfo.getOrderNo());
                }
            }
        }
    }

    // 修改订单  非收藏骑手也能看到此订单
    private static void updateIsSpecifiedPostmen(String orderNo) {
        StringBuffer sql = new StringBuffer();
        sql.append("update ").append(PojoTables.OrderInfo).append(" set isSpecifiedPostmen = 0").append(" where orderNo='").append(orderNo).append("'")
                .append(" and delFlag =0");
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("------------订单更新收藏骑手优先其他骑手失败-------------" + orderNo);
        }
        OrderInfoMemory.getInstance().modifyStatus(orderNo);
    }


    // 检测订单是否超时，若是超时了 则修改订单的记录，让其记录超时时间以及超时订单
    public static void checkOrderOverTime() {
        List<OrderInfo> orderInfoList = new ArrayList<>();
        synchronized (platformIngOrderList) {  //获得list锁对象，其他线程将不能获得list锁来来改变list对象。
            if (ValidateUtil.isAbsList(platformIngOrderList)) {
                orderInfoList.addAll(platformIngOrderList);
            }
            platformIngOrderList = new ArrayList<>();
        }


        if (ValidateUtil.isAbsList(orderInfoList)) {
//            StringBuffer s = new StringBuffer();
            // 判断时间是否需要修改等
            for (OrderInfo orderInfo : orderInfoList) {
//                s.append(orderInfo.getOrderNo()).append(",");
                modifyOrderTime(orderInfo);
            }
//            System.out.println(s.toString());
        }
    }

    // 检测订单是否超时  并修改
    private static void modifyOrderTime(OrderInfo orderInfo) {
        if (orderInfo == null) {
            return;
        }
        if (ValidateUtil.isNotAbsLong(orderInfo.getAgentId())) {
            return;
        }
        OrderOverTimeInfo orderOverTimeInfo = getAgentOverTimeInfoByAgentId(orderInfo.getAgentId());
        if (orderOverTimeInfo == null) {
            System.out.println("获取商圈订单超时设置失败");
            return;
        }
        if (orderOverTimeInfo.getIsOpen() == null || orderOverTimeInfo.getIsOpen() == 0) {
            // 关闭了  则不使用检测
            return;
        }
        boolean isUpdate = false;
        StringBuffer sql = new StringBuffer();
        sql.append("update ").append(PojoTables.OrderInfo).append(" set updateUser = 'admin'");
        // 外卖订单
        if (orderInfo.getOrderType() == ORDER_TYPE.SHOP_GOODS) {
            if (orderInfo.getIsZiQu() == 1) {
                // 不检测
            } else {
                // 配送单
                if (orderInfo.getShopSelfPost() != null
                        && orderInfo.getShopSelfPost() == 1) {
                    // 自配送订单
                    if (orderInfo.getIsOrderOverTime() != null
                            && orderInfo.getIsOrderOverTime() == 1
                            && orderInfo.getIsShopOverTime() != null
                            && orderInfo.getIsShopOverTime() == 1
                    ) {
                        isUpdate = false;
                    } else {
                        // 检测时间等
                        if ((orderInfo.getIsShopOverTime() == null || orderInfo.getIsShopOverTime() == 0)
                                && ValidateUtil.isNotAbsLong(orderInfo.getShopSureTime())
                                && orderOverTimeInfo.getShopOverTime() != null && orderOverTimeInfo.getShopOverTime() > 0
                                && DateUtils.getCurrTime() - orderInfo.getShopSureTime() > orderOverTimeInfo.getShopOverTime() * 60 * 1000L) {
                            sql.append(",isShopOverTime = 1").append(",agentShopOverTime = ").append(orderOverTimeInfo.getShopOverTime());
                            isUpdate = true;
                        }
                        // 检测订单时间
                        if ((orderInfo.getIsOrderOverTime() == null || orderInfo.getIsOrderOverTime() == 0)
                                && orderOverTimeInfo.getOrderOverTime() != null && orderOverTimeInfo.getOrderOverTime() > 0
                                && ValidateUtil.isAbsLong(orderInfo.getPayTime())
                                && orderInfo.getPayTime() != null && DateUtils.getCurrTime() - orderInfo.getPayTime() > orderOverTimeInfo.getOrderOverTime() * 60 * 1000L) {
                            sql.append(",isOrderOverTime = 1").append(",agentOrderOverTime = ").append(orderOverTimeInfo.getOrderOverTime());
                            isUpdate = true;
                        }
                    }
                } else {
                    // 平台配送的
                    if (orderInfo.getIsOrderOverTime() != null
                            && orderInfo.getIsOrderOverTime() == 1
                            && orderInfo.getIsShopOverTime() != null
                            && orderInfo.getIsShopOverTime() == 1
                            && orderInfo.getIsPostmanOverTime() != null
                            && orderInfo.getIsOrderOverTime() == 1
                    ) {
                        isUpdate = false;
                    } else {
                        // 检测时间等
                        // 店铺的
                        if ((orderInfo.getIsShopOverTime() != null || orderInfo.getIsShopOverTime() == 0)
                                && ValidateUtil.isAbsLong(orderInfo.getShopSureTime())
                                && orderOverTimeInfo.getShopOverTime() != null && orderOverTimeInfo.getShopOverTime() > 0
                                && DateUtils.getCurrTime() - orderInfo.getShopSureTime() > orderOverTimeInfo.getShopOverTime() * 60 * 1000L) {
                            sql.append(",isShopOverTime = 1").append(",agentShopOverTime = ").append(orderOverTimeInfo.getShopOverTime());
                            isUpdate = true;
                        }
                        // 检测订单时间
                        if ((orderInfo.getIsOrderOverTime() == null || orderInfo.getIsOrderOverTime() == 0)
                                && ValidateUtil.isAbsLong(orderInfo.getPayTime())
                                && orderOverTimeInfo.getOrderOverTime() != null && orderOverTimeInfo.getOrderOverTime() > 0
                                && orderInfo.getPayTime() != null && DateUtils.getCurrTime() - orderInfo.getPayTime() > orderOverTimeInfo.getOrderOverTime() * 60 * 1000L) {
                            sql.append(",isOrderOverTime = 1").append(",agentOrderOverTime = ").append(orderOverTimeInfo.getOrderOverTime());
                            isUpdate = true;
                        }
                        // 骑手时间
                        if (ValidateUtil.isNull(orderInfo.getPostmanName())) {
                        } else {
                            if ((orderInfo.getIsPostmanOverTime() != null || orderInfo.getIsPostmanOverTime() == 0)
                                    && ValidateUtil.isAbsLong(orderInfo.getPostmanSureTime())
                                    && orderOverTimeInfo.getPostmanOverTime() != null && orderOverTimeInfo.getPostmanOverTime() > 0
                                    && DateUtils.getCurrTime() - orderInfo.getPostmanSureTime() > orderOverTimeInfo.getPostmanOverTime() * 60 * 1000L) {
                                sql.append(",isPostmanOverTime=1").append(",agentPostmanOverTime=").append(orderOverTimeInfo.getPostmanOverTime());
                                isUpdate = true;
                            }
                        }
                        // 骑手接单但是未到店
                        if (ValidateUtil.isAbsLong(orderInfo.getPostmanSureTime())
                                && (orderInfo.getOrderStatus() == ORDER_STATUS.SHOP_SURE
                                || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_SURE)
                                && ValidateUtil.isAbsInteger(orderOverTimeInfo.getNotTakenOrderTime())
                                && orderOverTimeInfo.getNotTakenOrderTime() > 0
                                && DateUtils.getCurrTime() - orderInfo.getPostmanSureTime() > orderOverTimeInfo.getNotTakenOrderTime() * 60 * 1000L) {
                            sql.append(",isNotTakenOrderTime=1").append(",agentNotTakenOrderTime=").append(orderOverTimeInfo.getNotTakenOrderTime());
                            isUpdate = true;
                        }
                    }
                }
            }
        } else if (orderInfo.getOrderType() == ORDER_TYPE.PAO_TUI
                || orderInfo.getOrderType() == ORDER_TYPE.DAI_GOU
                || orderInfo.getOrderType() == ORDER_TYPE.BANG_BAN
                || orderInfo.getOrderType() == ORDER_TYPE.HUO_YUN
        ) {

            if (orderInfo.getIsOrderOverTime() != null
                    && orderInfo.getIsOrderOverTime() == 1
                    && orderInfo.getIsPostmanOverTime() != null
                    && orderInfo.getIsOrderOverTime() == 1
            ) {
                isUpdate = false;
            } else {
                // 订单是否超时了
                // 检测订单时间
                if ((orderInfo.getIsOrderOverTime() == null || orderInfo.getIsOrderOverTime() == 0)
                        && orderOverTimeInfo.getOrderOverTime() != null && orderOverTimeInfo.getOrderOverTime() > 0
                        && ValidateUtil.isAbsLong(orderInfo.getPayTime())
                        && orderInfo.getPayTime() != null && DateUtils.getCurrTime() - orderInfo.getPayTime() > orderOverTimeInfo.getOrderOverTime() * 60 * 1000L) {
                    sql.append(",isOrderOverTime = 1").append(",agentOrderOverTime = ").append(orderOverTimeInfo.getOrderOverTime());
                    isUpdate = true;
                }
                // 骑手订单是否已经超时了么
                if (ValidateUtil.isNull(orderInfo.getPostmanName())) {
                } else {
                    if ((orderInfo.getIsPostmanOverTime() != null || orderInfo.getIsPostmanOverTime() == 0)
                            && ValidateUtil.isAbsLong(orderInfo.getPostmanSureTime())
                            && orderOverTimeInfo.getPostmanOverTime() != null && orderOverTimeInfo.getPostmanOverTime() > 0
                            && DateUtils.getCurrTime() - orderInfo.getPostmanSureTime() > orderOverTimeInfo.getPostmanOverTime() * 60 * 1000L) {
                        sql.append(",isPostmanOverTime=1").append(",agentPostmanOverTime=").append(orderOverTimeInfo.getPostmanOverTime());
                        isUpdate = true;
                    }
                }
            }
        }
        sql.append(" where orderNo='").append(orderInfo.getOrderNo()).append("' and delFlag =0");
        if (isUpdate) {
            try {
                UserDaoSql.getInstance().executeBySql(sql.toString());
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("订单超时检测异常------》orderNo=" + orderInfo.getOrderNo() + "异常：" + e.getMessage());
            }
            // 缓存
            OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
        }
    }

    // 获取商圈设置
    private static OrderOverTimeInfo getAgentOverTimeInfoByAgentId(Long agentId) {
        if (agentId == null) {
            return null;
        }
        OrderOverTimeInfo info = AgentOrderOverTimeMemory.getInstance().getAgentOrderOverTimeInfoByAgentId(agentId);
        if (info == null) {
            info = AgentOrderOverTimeMemory.getInstance().getPlateDefaultSetting();
        }
        return info;
    }

    // 获取平台正在进行中的订单
    public static List<OrderInfo> getPlatformIngOrderList() {
        List<OrderInfo> orderInfoList = OrderInfoMemory.getInstance().listOfIngPlatFormOrderList();
        if (ValidateUtil.isAbsList(orderInfoList)) {
            List<OrderInfo> list = new ArrayList<>();
            for (OrderInfo orderInfo : orderInfoList) {
                if (orderInfo == null) {
                    continue;
                }
                if (isNeedCheckOverTime(orderInfo)) {
                    list.add(orderInfo);
                }
            }
            if (ValidateUtil.isAbsList(list)) {
                return list;
            }
        }
        return null;
    }

    private static boolean isNeedCheckOverTime(OrderInfo orderInfo) {
        if (orderInfo == null) {
            return false;
        } else {
            // 商家的
            if (orderInfo.getOrderType() == ORDER_TYPE.SHOP_GOODS) {
                // 购物的
                if (orderInfo.getIsZiQu() == 1) {
                    // 自取
                    if ((orderInfo.getIsShopOverTime() != null
                            && orderInfo.getIsShopOverTime() == 1
                            && orderInfo.getIsOrderOverTime() != null
                            && orderInfo.getIsOrderOverTime() == 1)) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    // 配送订单
                    if (orderInfo.getShopSelfPost() != null && orderInfo.getShopSelfPost() == 1) {
                        // 自配送的
                        if ((orderInfo.getIsShopOverTime() != null
                                && orderInfo.getIsShopOverTime() == 1
                                && orderInfo.getIsOrderOverTime() != null
                                && orderInfo.getIsOrderOverTime() == 1)) {
                            return false;
                        } else {
                            return true;
                        }
                    } else {
                        // 平台配送的
                        if ((orderInfo.getIsShopOverTime() != null
                                && orderInfo.getIsShopOverTime() == 1
                                && orderInfo.getIsOrderOverTime() != null
                                && orderInfo.getIsOrderOverTime() == 1)
                                && orderInfo.getIsNotTakenOrderTime() != null
                                && orderInfo.getIsNotTakenOrderTime() == 1
                                && orderInfo.getIsPostmanAdvanceTime() != null
                                && orderInfo.getIsPostmanAdvanceTime() == 1
                                && orderInfo.getIsPostmanOverTime() != null
                                && orderInfo.getIsPostmanOverTime() == 1) {
                            return false;
                        } else {
                            return true;
                        }
                    }
                }
            } else {
                // 跑腿代购等
                if (ORDER_TYPE.PAO_TUI == orderInfo.getOrderType()
                        || ORDER_TYPE.DAI_GOU == orderInfo.getOrderType()
                        || ORDER_TYPE.BANG_BAN == orderInfo.getOrderType()
                        || ORDER_TYPE.HUO_YUN == orderInfo.getOrderStatus()) {
                    if (orderInfo.getIsOrderOverTime() != null
                            && orderInfo.getIsOrderOverTime() == 1
                            && orderInfo.getIsPostmanOverTime() != null
                            && orderInfo.getIsPostmanOverTime() == 1) {
                        return false;
                    } else {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    //-----------------------新订单电话通知
    public static void noticeShopNewOrder() {
        // 获取所有未接单订单
        // <商家账号，订单列表>
        ConcurrentHashMap<Long, HashSet<String>> shopNotSureMap = OrderInfoMemory.getInstance().getAllShopNotSureOrder();
        if (null == shopNotSureMap) {
            return;
        }
        if (shopNotSureMap.size() <= 0) {
            return;
        }

        String sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
        if (ValidateUtil.isNull(sysAppKey)) {
            return;
        }
        Integer noticeTime = SYS_SETTINGS.SHOP_NEW_ORDER_PHONE;
        Long nowTime = DateUtils.getCurrTime();
        synchronized (shopNotSureMap) {
            for (Map.Entry<Long, HashSet<String>> data : shopNotSureMap.entrySet()) {
                Long shopId = data.getKey();// 店铺Id
                if (ValidateUtil.isNotID(shopId)) {
                    continue;
                }
                HashSet<String> set = data.getValue();
                if (null == set || set.size() < 1) {
                    // 该店铺没有订单
                    continue;
                }
                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
                if (null == shopInfo || ValidateUtil.isNull(shopInfo.getTelephone())) {
                    // 店铺已不存在
                    continue;
                }

                // 店铺设置的不需要电话通知
                if (null != shopInfo.getNeedCall() && 0 == 1 - shopInfo.getNeedCall()) {
                } else {
                    continue;
                }

                OrderInfo order = null;// 需要通知的订单
                for (String orderNo : set) {
                    if (ValidateUtil.isNull(orderNo)) {
                        continue;
                    }
                    OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
                    if (null == orderInfo || ValidateUtil.isNotAbsLong(orderInfo.getPayTime())) {
                        continue;
                    }

                    // 订单类型
                    if (null == orderInfo.getOrderType()) {
                        continue;
                    }
                    if (0 == ORDER_TYPE.SHOP_GOODS - orderInfo.getOrderType()) {

                    } else {
                        continue;
                    }

                    // 判断订单状态
                    if (0 == ORDER_STATUS.PAYED - orderInfo.getOrderStatus()) {
                    } else {
                        continue;
                    }

                    // 是否通知过
                    OrderInfoExtra extra = OrderInfoExtraMemory.getInstance().getOrderInfoExtraByOrderNo(orderNo);
                    if (null == extra) {
                        // 没有订单额外信息
                        extra = new OrderInfoExtra();
                        extra.setOrderNo(orderNo);
                        extra.setCreateTime(DateUtils.getCurrTime());
                        extra.setDelFlag(0);
                        extra.setCreateUser("admin");
                        try {
                            UserDaoSql.getInstance().insertObj(PojoTables.ORDER_INFO_EXTRA, extra);
                        } catch (SQLException e) {
                            e.printStackTrace();
                            continue;
                        }

                        OrderInfoExtraMemory.getInstance().add(orderNo);

                        extra = OrderInfoExtraMemory.getInstance().getOrderInfoExtraByOrderNo(orderNo);
                    }
                    if (null == extra) {
                        continue;
                    }
                    if (null == extra.getNoticeTime() || extra.getNoticeTime() < 1) {
                        // 未通知过
                    } else {
                        // 已通知
                        continue;
                    }

                    // 是否到了通知时间
                    if (nowTime - orderInfo.getPayTime() > noticeTime * 60 * 1000) {
                        // 需要通知
                        order = orderInfo;
                        break;
                    }
                }

                // 是否有订单需要通知
                if (null != order && ValidateUtil.isNotNull(order.getOrderNo())) {
                    boolean callSuccess = PhoneNotice.callPhone(sysAppKey, shopInfo.getTelephone(), PONE_NOTICE_TYPE.SHOP_NEW_ORDER, "请尽快接单");
                    if (!callSuccess) {
                        continue;
                    }

                    // 通知后记录通知时间
                    StringBuffer sb = new StringBuffer();
                    sb.append("update ").append(PojoTables.ORDER_INFO_EXTRA)
                            .append(" set noticeTime= ").append(DateUtils.getCurrTime())
                            .append(" where orderNo = '").append(order.getOrderNo()).append("'");
                    try {
                        UserDaoSql.getInstance().executeUpdateBySql(sb.toString());
                    } catch (SQLException e) {
                        e.printStackTrace();
                        continue;
                    }
                    OrderInfoExtraMemory.getInstance().modify(order.getOrderNo());
                }
            }
        }
    }


    public static void main(String[] args) {
        try {
            List<TtsCallResponseInfo> list = TelCallClient.getInstance().setSysCustomer("iot-beiren").setPhone("15666371607").setType("tts_alarm_notice").setParam("location", "公司").setParam("equipment", "订单11122220001").setParam("event", "请尽快接单").telCall();
            System.out.println(JSON.toJSON(list));
        } catch (TelCallException var2) {
            var2.printStackTrace();
        }
    }

    //-----------------------自动派单
    synchronized public static void dispatchOrder() {
        // 获取所有需要派单的订单
        HashSet<String> needSet = needDispatchOrderSet;
        if (null == needSet || needSet.size() < 1) {
            return;
        }
        for (String orderNo : needSet) {
            if (ValidateUtil.isNull(orderNo)) {
                continue;
            }
            ResultInfo dispatchSuccess = DispatchPostmanBusinessV2.dispatch(orderNo, "sadmin");
            if (null == dispatchSuccess) {

            } else {
                if (dispatchSuccess.isSuccess()) {
                    // 派单成功
                    removeDispatchOrder(orderNo);
                }
            }
        }
    }

    public static void addNeedDispatchOrder(String orderNo) {
        // 系统是否开启了自动派单
        if (null == SYS_SETTINGS.IS_OPEN_AUTO_DISPATCH_ORDER || 0 == SYS_SETTINGS.IS_OPEN_AUTO_DISPATCH_ORDER) {
            return;
        }
        needDispatchOrderSet.add(orderNo);
        dispatchOrder();
    }

    public static void removeDispatchOrder(String orderNo) {
        if (needDispatchOrderSet.contains(orderNo)) {
            needDispatchOrderSet.remove(orderNo);
        }
    }

    // ------------- 聚合订单 商家接单检测

    public static void checkMultipleOrder() {
        // 查询订单
        HashSet<String> hashSet = OrderInfoMemory.getInstance().listOfParentMultipleOrder(ORDER_STATUS.PAYED);
        if (hashSet == null) {
            return;
        }
        for (String parent : hashSet) {
            try {
                checkMultipleOrderAllShopSure(parent);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("聚合订单检测任务失败");
            }
        }


    }

    public static void checkMultipleOrderAllShopSure(String parentOrderNo) throws Exception {
        if (!OrderMan.isMultipleParentOrder(parentOrderNo)) {
            throw new Exception("您选择的订单有误");
        }
        OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(parentOrderNo);
        if (info == null) {
            throw new Exception("获取订单信息错误");
        }
        if (info.getOrderStatus() == ORDER_STATUS.PAYED) {
            HashSet<String> hashSet = OrderInfoMemory.getInstance().listOfParentOrderNo(parentOrderNo);
            boolean isShopSure = false;
            if (hashSet == null) {
                isShopSure = true;
            } else {
                for (String ono : hashSet) {
                    OrderInfo info1 = OrderInfoMemory.getInstance().getOrderInfo(ono);
                    if (info1 == null) {
                        continue;
                    }
                    if (info1.getOrderStatus() == ORDER_STATUS.PAYED
                            || info1.getOrderStatus() == ORDER_STATUS.SHOP_REFUSED
                            || info1.getOrderStatus() == ORDER_STATUS.CANCEL
                            || info1.getOrderStatus() == ORDER_STATUS.PAYED_CANCEL
                            || info1.getOrderStatus() == ORDER_STATUS.CANCEL_BY_SYSTEM) {
                        isShopSure = false;
                    } else {
                        isShopSure = true;
                    }
                }
            }
            if (isShopSure) {
                String shopSureTime = ",shopSureTime=" + DateUtils.getCurrTime();
                if (!OrderMan.modifyOrderStatus("admin", parentOrderNo, ORDER_STATUS.SHOP_SURE, shopSureTime)) {
                    throw new Exception("操作失败，请稍后再试");
                }
            }
        }
    }

    // 哒哒自动订单完成查询
    public static void autoOrderDadaQueryStates() {
        Set<Integer> orderStatusSet = new HashSet<>();
        orderStatusSet.add(ORDER_STATUS.CANCEL);
        orderStatusSet.add(ORDER_STATUS.CANCEL_BY_SYSTEM);
        orderStatusSet.add(ORDER_STATUS.PAYED_CANCEL);
        orderStatusSet.add(ORDER_STATUS.SUBMIT);
        orderStatusSet.add(ORDER_STATUS.OVER);
        orderStatusSet.add(ORDER_STATUS.POSTMAN_FINISH);

        StringBuffer sql = new StringBuffer();
        sql.append(" select * from ").append(PojoTables.OrderInfo)
                .append(" where orderStatus not in (").append(StringUtils.join(orderStatusSet, ",")).append(")")
                .append(" and isOtherPost = 1 ")
                .append(" and delFlag = 0 ").append(" and isRefundApply != ").append(REFUND_APPLY_STATUS.PASS);
        List<OrderInfo> list = null;
        try {
            list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!ValidateUtil.isAbsList(list)) {
            return;
        }
        for (OrderInfo orderInfo : list) {
            queryOrderDadaStatus(orderInfo);
        }
    }

    // c
    private static void queryOrderDadaStatus(OrderInfo orderInfo) {
        String sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
        DeliveryOrderStateTO orderStateTO = ShopOrderService.getInstance().queryDeliveryOrderState(sysAppKey, orderInfo.getOrderNo());
        if (orderStateTO != null) {
            try {
                ShopOrderService.getInstance().dealDeliveryOrderState(orderStateTO, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    // 查询保险处理
    public static void dealThreadBaoXian() {
        List<OrderInfo> orderInfos = listOfBuyInBuyInsuranceOrder();
        for (OrderInfo orderInfo : orderInfos) {
            queryAndUpdateThreadPolicy(orderInfo);
        }
    }

    /**
     * 查询第三方的数据
     *
     * @return
     */
    public static void queryAndUpdateThreadPolicy(OrderInfo orderInfo) {
        String orderNo = orderInfo.getOrderNo();
        List<PolicyInfo> list = OrderPolicyRecordMemory.getInstance().listOfOrderNo(orderNo);
        Set<Integer> statusSet = new HashSet<>();
        if (orderInfo.getIsRefundApply() == REFUND_APPLY_STATUS.PASS || ORDER_STATUS.userOrderCancelSet.contains(orderInfo.getOrderStatus())) {

        } else {
            list = list.stream().filter(item -> {
                if (INSURANCE_STATUS.alreadyDealStatusSet.contains(item.getStatus())) {
                    statusSet.add(item.getStatus());
                    return false;
                }
                return true;
            }).collect(Collectors.toList());
        }

        if (ValidateUtil.isAbsList(list)) {
            for (PolicyInfo info : list) {
                // 查询数据
                String requretStr = HttpRequest.sendPost(SYS_CONFIG_PATH.BAO_XIAN_SERVICE_URL + "/policy/listByOrderNo"
                        , "orderNo=" + info.getOrderNoIndex());
                PolicyResultDto policyResultDto = new Gson().fromJson(requretStr, PolicyResultDto.class);
                if (null == policyResultDto) {
                    System.out.println("投保服务器未响应信息");
                }
                if (0 == policyResultDto.getStatus()) {
                    System.out.println("投保信息处理失败 " + policyResultDto.getError());
                }
                List<PolicyInfoVO> infoList = policyResultDto.getData();
                if (ValidateUtil.isAbsList(infoList)) {
                    Connection conn = null;
                    try {
                        conn = UserDaoSql.getInstance().getConnection();
                        conn.setAutoCommit(false);
                        for (PolicyInfoVO temp : infoList) {
                            statusSet.add(temp.getStatus());
                            String sql = "update " + PojoTables.ORDER_POLICY_RECORD + " set status = " + temp.getStatus();
                            if (ValidateUtil.isNotNull(temp.getPolicyNum())) {
                                sql += " , policyNum = '" + temp.getPolicyNum() + "' ";
                            }
                            if (ValidateUtil.isNotNull(temp.getPolicyNo())) {
                                sql += " , policyNo = '" + temp.getPolicyNo() + "' ";
                            }
                            sql += " where delFlag = 0 and orderNo ='" + orderNo + "' and orderNoIndex = '" + temp.getOrderNo() + "' ";
                            UserDaoSql.getInstance().executeBySql(sql.toString(), conn);
                        }
                        conn.commit();
                    } catch (Exception e) {
                        e.getMessage();
                        System.out.println("查询第三方保单失败~~~");
                        UserDaoSql.getInstance().rollback(conn);
                    } finally {
                        UserDaoSql.getInstance().close(conn);
                    }
                }
            }
            if (orderInfo != null && orderInfo.getInsuranceStatus() != null && !statusSet.isEmpty()) {
                int status = 0;
                if (statusSet.size() == 1) {
                    status = statusSet.iterator().next();
                } else {
                    status = INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.INSURANCE_EXIST_ERR;
                }
                if (status - orderInfo.getInsuranceStatus() != 0) {
                    String updateSql = " update " + PojoTables.OrderInfo + " set insuranceStatus = " + status + " where orderNo ='" + orderNo + "' and delFlag = 0";
                    try {
                        UserDaoSql.getInstance().executeBySql(updateSql);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    OrderInfoMemory.getInstance().modifyStatus(orderNo);
                }
            }
        }
    }


    /**
     * 查询购买的订单
     *
     * @return
     */
    private static List<OrderInfo> listOfBuyInBuyInsuranceOrder() {
//        String sql = "select orderNo,payTime,orderStatus from " + PojoTables.OrderInfo + " where delFlag = 0 and isPaid = 1 and payTime >" + (DateUtils.getCurrTime() - 30 * 60 * 1000L)
//                + " and orderType =" + ORDER_TYPE.PERSON_TRANSPORT + " and orderStatus not in (" + StringUtils.join(ORDER_STATUS.userOrderCancelSet, ",")
//                + ") and insuranceStatus in (" + StringUtils.join(INSURANCE_STATUS.waitForDealStatusSet, ",") + ") and insuranceStatus = 1";
//        List<OrderInfo> list = null;
//        try {
//            list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sql.toString());
//        } catch (Exception e) {
//            e.getMessage();
//        }
//        return ValidateUtil.isAbsList(list) ? list : Collections.emptyList();
        List<OrderInfo> list = OrderInfoMemory.getInstance().listOfOrderInfo();
        if (!ValidateUtil.isAbsList(list)) {
            return Collections.emptyList();
        }
        Long nowTime = DateUtils.getCurrTime();
        return list.stream().filter(item -> {
            if (item.getIsBuyInsurance() == null || item.getIsBuyInsurance() != 1) {
                return false;
            }
            if (item.getOrderType() == null || item.getOrderType() - ORDER_TYPE.PERSON_TRANSPORT != 0) {
                return false;
            }
            if ((item.getInsuranceStatus() == null || !INSURANCE_STATUS.waitForDealStatusSet.contains(item.getInsuranceStatus())) && item.getIsRefundApply() != REFUND_APPLY_STATUS.PASS) {
                return false;
            }
            // 已经取消了订单
            if (ORDER_STATUS.userOrderCancelSet.contains(item.getOrderStatus())
                    && (
                    item.getInsuranceStatus() - INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.BACK_FAIL == 0
                            || item.getInsuranceStatus() - INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.BACK_SUCCESS == 0)) {
                return false;
            }
            Long cTime = item.getCreateTime();
            if (ValidateUtil.isNotAbsLong(cTime)) {
                cTime = item.getCreateTime();
            }
            if (ValidateUtil.isNotAbsLong(cTime)) {
                return false;
            }
            if (nowTime - 24 * 60 * 60 * 1000L > cTime) {
                return false;
            }
            return true;
        }).collect(Collectors.toList());
    }

    // 查询未处理的保险
    public static List<PolicyInfo> unDealPolicyList() {
        Long time = DateUtils.getCurrTime() - 3 * 24 * 60 * 60 * 1000L;
        /**
         *  个保
         */
//        String sql = "select * from " + PojoTables.ORDER_POLICY_RECORD + " WHERE delFlag = 0 and updateTime > " + time + " and status = " + INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.INSURANCE_SELF_UNDEAL
//                + " and type = 2";
//        List<PolicyInfo> list = null;
//        try {
//            list = (List<PolicyInfo>) UserDaoSql.getInstance().list(PolicyInfo.class, sql);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return list;
        List<PolicyInfo> infoList = OrderPolicyRecordMemory.getInstance().listAll();
        if (ValidateUtil.isAbsList(infoList)) {
            return infoList.stream().filter(item -> {
                // 只查询最近三天并且是已经支付的未取消的保单信息
                if (item.getIsCancel() != 0 || item.getIsOrderPaid() != 1 || item.getCreateTime() < time || item.getStatus() - INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.INSURANCE_SELF_UNDEAL != 0) {
                    return false;
                }
                return true;
            }).collect(Collectors.toList());
        } else {
            return Collections.emptyList();
        }
    }


    /**
     * 查询正在转单的订单
     */
    public static void autoFinishChangePostman() {
        Long time = DateUtils.getCurrTime() - SYS_SETTINGS.AUTO_FINISH_CHANGE_POSTMAN_TIME * 60 * 1000L;
        StringBuilder sql = new StringBuilder();
        sql.append(" select orderNo,orderStatus,postManUsername, changePostman, changePostmanTime, isReGrab from ").append(PojoTables.OrderInfo)
                .append(" where delFlag = 0 and changePostman is not null ")
                .append(" and changePostmanTime <").append(time);
        List<OrderInfo> orderInfos = null;
        try {
            orderInfos = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ValidateUtil.isAbsList(orderInfos)) {
            for (OrderInfo orderInfo : orderInfos) {
                autoFinishChangePostmanOrderInfo(orderInfo);
            }
        }
    }

    // 确定接单
    public static void autoFinishChangePostmanOrderInfo(OrderInfo orderInfo) {
        if (orderInfo == null) {
            return;
        }
        if (ValidateUtil.isNull(orderInfo.getChangePostman())) {
            return;
        }
        CityPostman postman = CityPostmanMemory.getInstance().getPostman(orderInfo.getChangePostman());
        if (null == postman) {
            return;
        }

        if (1 == postman.getIsLock() || 0 == postman.getIsWork()) {
            return;
        }

        ResultInfo resultInfo = OrderMan.postmanSureOrRefuse(orderInfo.getOrderNo(), postman.getUsername(), OrderPostmanInfo.SURE);
        if (resultInfo == null) {
            System.out.println("~自动转单失败~" + orderInfo.getOrderNo());
        } else if (!resultInfo.isSuccess()) {
            System.out.println("~自动转换失败~ orderNo:" + orderInfo.getOrderNo() + "; 错误信息:" + resultInfo.getMessage());
        }
    }

    // 团购订单自动取消订单
    public static void groupOrderExpiredCheck() {
        /**
         * SELECT
         *   OG.orderNo,
         *   OG.expiryTimes
         * FROM
         *   order_info AS O
         *   INNER JOIN order_goods AS OG
         *     ON OG.orderNo = O.orderNo
         * WHERE O.delFlag = 0
         *   AND O.isPaid = 1
         *   AND O.orderType = 16
         *   AND O.orderStatus = 5
         *   AND OG.delFlag = 0
         *   AND O.isRefundApply != 2
         *   AND OG.expiryTimes IS NOT NULL
         *   AND OG.expiryTimes != ''
         */
        // 自动取消订单
        StringBuilder sql = new StringBuilder();
        sql.append(" select OG.orderNo,OG.expiryTimes from ")
                .append(PojoTables.OrderInfo).append(" as O ")
                .append(" inner join ")
                .append(PojoTables.OrderGoods).append(" AS OG ")
                .append(" on OG.orderNo = O.orderNo ")
                .append(" where O.delFlag = 0 ")
                .append(" AND O.isPaid = 1  ")
                .append("  AND O.orderType = ").append(ORDER_TYPE.GROUP_ORDER)
                .append(" AND O.orderStatus = ").append(ORDER_STATUS.SHOP_SURE)
                .append(" AND OG.delFlag =  0 ")
                .append(" and  O.isRefundApply !=").append(REFUND_APPLY_STATUS.PASS)
                .append(" AND OG.expiryTimes IS NOT NULL  AND OG.expiryTimes != '' ");
        List<OrderGoodsVO> list = null;
        try {
            list = (List<OrderGoodsVO>) UserDaoSql.getInstance().list(OrderGoodsVO.class, sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("查询失效订单失败 请稍后稍后重试");
            return;
        }
        if (!ValidateUtil.isAbsList(list)) {
            return;
        }
        Set<String> needCancelOrderSet = new HashSet<>();
        Date local = new Date();
        for (OrderGoodsVO orderGoods : list) {
            if (isExpiredGroupOrder(orderGoods, local)) {
                needCancelOrderSet.add(orderGoods.getOrderNo());
            }
        }
        if (needCancelOrderSet != null && !needCancelOrderSet.isEmpty()) {
            for (String orderNo : needCancelOrderSet) {
                //取消订单
                OrderInfo orderInfo = findOrderByOrderNo(orderNo);
                if (orderInfo == null) {
                    continue;
                }
                ResultInfo resultInfo = OrderMan.cancelOrder(null, orderInfo, "admin", "优惠券过期自动取消", true);
                if (resultInfo == null) {
                    System.out.println(" 优惠券到期取消订单失败了 [" + orderNo + "]");
                } else if (null != resultInfo && resultInfo.isSuccess()) {
                    System.out.println(" 优惠券到期自动取消成功 ");
                } else {
                    System.out.println(" 优惠券到期取消订单失败~~~[" + orderNo + "]" + resultInfo.getError());
                }
            }
        }
    }

    // 是不是过期的订单
    private static boolean isExpiredGroupOrder(OrderGoodsVO orderGoods, Date local) {
        if (ValidateUtil.isNull(orderGoods.getExpiryTimes())) {
            return false;
        }
        String dateFormatStr = orderGoods.getExpiryTimes() + " 23:59:59";
        Date date = null;
        try {
            date = DateUtils.sdfDateTime.get().parse(dateFormatStr);
        } catch (Exception e) {
            return false;
        }
        if (date == null) {
            return false;
        }
        return date.before(local);
    }

    private static OrderInfo findOrderByOrderNo(String orderNo) {
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (orderInfo == null) {
            StringBuilder sql = new StringBuilder();
            sql.append(" select * from ").append(PojoTables.OrderInfo)
                    .append(" where delFlag = 0 and orderNo ='").append(orderNo).append("' limit 0,1");
            try {
                orderInfo = (OrderInfo) UserDaoSql.getInstance().getObject(OrderInfo.class, sql.toString());
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return orderInfo;
    }

}
